package com.cnpc.iot.dform.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnpc.framework.base.dao.BaseDao;
import com.cnpc.framework.base.entity.Dict;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.pojo.FieldSetting;
import com.cnpc.framework.query.entity.QueryCondition;
import com.cnpc.framework.utils.DateUtil;
import com.cnpc.framework.utils.SecurityUtil;
import com.cnpc.iot.dform.service.DformService;
import com.cnpc.iot.scgl.entity.Dfiled;
import com.cnpc.iot.scgl.entity.Pnode;

@Service
public class DformServiceImpl implements DformService {

	@Autowired
	private BaseDao baseDao;

	@Override
	public Map<String, Object> createDform(QueryCondition queryCondition, String nodeId) {
		Pnode pnode = baseDao.get("from Pnode where id='" + nodeId + "'");
		List<Dfiled> flist = baseDao.find("from Dfiled where nodeId='" + pnode.getId() + "' order by orderId");
		Map<String, Object> query = new HashMap<>();
		query.put("id", queryCondition.getQueryId());
		query.put("key", "id");
		query.put("countStr", "count(*)");
		query.put("tableName", pnode.getCode());
		query.put("pagesize", 10);
		query.put("pagesInGrp", 5);
		query.put("widthType", "px");
		query.put("allowPaging", true);
		query.put("enableMultiline", true);
		query.put("isServerFilter", false);
		query.put("enableMultiHeader", false);
		query.put("simpleSearch", true);
		query.put("startRow", 1);

		List<Map<String, Object>> columnList = new ArrayList<>();
		Map<String, Map<String, Object>> columnMap = new HashMap<>();
		StringBuffer sql = new StringBuffer();
		sql.append("select id, parent, creater, optime, fileids, ");
		
		columnList.add(createParentFiled("parent", "PARENT", "java.lang.String", true, null, null));
		columnMap.put("parent", createParentFiled("parent", "PARENT", "java.lang.String", true, null, null));
		
		columnList.add(createParentFiled("creater", "创建人", "java.lang.String", false, null, null));
		columnMap.put("creater", createParentFiled("creater", "创建人", "java.lang.String", false, null, null));
		
		columnList.add(createParentFiled("optime", "创建日期", "java.util.Date", false, "yyyy-mm-dd hh:ii:ss", null));
		columnMap.put("optime", createParentFiled("optime", "创建日期", "java.util.Date", false, "yyyy-mm-dd hh:ii:ss", null));
		
		columnList.add(createParentFiled("fileids", "IMAGES", "java.lang.String", true, null, null));
		columnMap.put("fileids", createParentFiled("fileids", "IMAGES", "java.lang.String", true, null, null));
		
		if (null != flist && flist.size() > 0) {
			
			for (int i = 0; i < flist.size(); i++) {
				Dfiled f = flist.get(i);
				Map<String, Object> colMap = createFiled(f);
				columnList.add(colMap);
				columnMap.put(f.getCode(), colMap);
				sql.append(f.getCode());
				if (i < flist.size() - 1) {
					sql.append(", ");
				}
			}
		}
		columnList.add(createParentFiled("showimg", "现场图片", "java.lang.String", false, null, "id"));
		columnMap.put("id", createParentFiled("showimg", "现场图片", "java.lang.String", true, null, "id"));
		
		sql.append(" from dny_" + pnode.getCode());
		String parent = (String) queryCondition.getConditions().get(0).get("value");
		sql.append(" where parent='" + parent + "'");
		System.out.println("=========sqls: " + sql.toString());
		query.put("sql", sql.toString());
		query.put("columnList", columnList);
		query.put("columnMap", columnMap);

		List<Map<String, Object>> rows = baseDao.findMapBySql(sql.toString());

		Map<String, Object> pageInfo = new HashMap<>();
		pageInfo.put("pageNum", 1);
		pageInfo.put("pageSize", 10);
		pageInfo.put("count", rows.size());// TODO
		pageInfo.put("pageCount", 1);
		pageInfo.put("pojoList", new ArrayList<>());

		Map<String, Object> result = new HashMap<>();
		result.put("query", query);
		result.put("pageInfo", pageInfo);
		result.put("rows", rows);
		return result;
	}

	private Map<String, Object> createFiled(Dfiled filed) {
		Dict dict = baseDao.get(Dict.class, filed.getFtype());
		Map<String, Object> map = new HashMap<>();
		map.put("key", filed.getCode());
		map.put("id", null);
		map.put("header", filed.getName());
		map.put("type", "ro");
		map.put("classType", dict.getValue());
		map.put("align", "center");
		map.put("allowSort", false);
		map.put("allowSearch", false);
		map.put("hidden", filed.getFview().equals("1") ? false : true);
		map.put("enableTooltip", false);
		map.put("color", "");
		map.put("operator", "eq");
		map.put("width", "100");
		if(dict.getValue().equals("java.util.Date")) {
			map.put("dateFormat", "yyyy-mm-dd hh:ii:ss");
		}else {
			map.put("dateFormat", null);
		}
		map.put("numberFormat", null);
		map.put("fnRender", null);
		map.put("isServerCondition", false);
		map.put("value", null);
		map.put("isExport", true);
		map.put("suffix", null);
		map.put("dict", null);
		map.put("maxLen", null);
		map.put("tooltip", null);
		map.put("isJustExport", false);
		map.put("subHeader", "#rspan");
		map.put("render", null);
		map.put("isQuote", true);
		map.put("isImport", true);
		map.put("index", null);
		map.put("foreignClass", null);
		map.put("isShow", null);
		map.put("operatorObject", new HashMap<String, String>().put("string", "%0 = %1"));
		return map;
	}
	
	private Map<String, Object> createParentFiled(String key, String header, String classType, boolean hidden, String dateFormat, String id) {
		Map<String, Object> map = new HashMap<>();
		map.put("key", key);
		map.put("id", id);
		map.put("header", header);
		map.put("type", "ro");
		map.put("classType", classType);
		map.put("align", "center");
		map.put("allowSort", false);
		map.put("allowSearch", false);
		map.put("hidden", hidden);
		map.put("enableTooltip", false);
		map.put("color", "");
		map.put("operator", "eq");
		map.put("width", "100");
		map.put("dateFormat", dateFormat);
		map.put("numberFormat", null);
		if(null == id) {
			map.put("fnRender", null);
		}else {
			map.put("fnRender", "fnRenderOperator");
		}
		map.put("isServerCondition", false);
		map.put("value", null);
		map.put("isExport", true);
		map.put("suffix", null);
		map.put("dict", null);
		map.put("maxLen", null);
		map.put("tooltip", null);
		map.put("isJustExport", false);
		map.put("subHeader", "#rspan");
		map.put("render", null);
		map.put("isQuote", true);
		map.put("isImport", true);
		map.put("index", null);
		map.put("foreignClass", null);
		map.put("isShow", null);
		map.put("operatorObject", new HashMap<String, String>().put("string", "%0 = %1"));
		return map;
	}

	@Override
	public List<Map<String, Object>> querySql(String nodeId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int deleteSql(String nodeId, String id) {
		Pnode pnode = baseDao.get(Pnode.class, nodeId);
		String sql = "delete from dny_" + pnode.getCode()+" where id='"+id+"'";
		return baseDao.executeSql(sql);
	}

	@Override
	public int insertSql(String nodeId, String parent, String fileids, Map<String, Object> parame) {
		User user = SecurityUtil.getUser();
		String creater = "";
		if(null != user) {
			creater = user.getName();
		}
		Pnode pnode = baseDao.get(Pnode.class, nodeId);
		List<Dfiled> dfList = baseDao.find("from Dfiled where nodeId='"+nodeId+"' order by orderId");
		if(null != pnode) {
			String table = "dny_"+pnode.getCode();
			StringBuffer sbVal = new StringBuffer(" values (");
			StringBuffer sb = new StringBuffer();
			sb.append("insert into ");
			sb.append(table);
			sb.append(" (id, parent, creater, optime, fileids, ");
			sbVal.append("'"+UUID.randomUUID().toString()+"', '" + parent + "', ");
			sbVal.append("'" + creater + "', now(), '" + fileids + "', ");
			int index = 1;
			for(Dfiled df : dfList) {
				sb.append(df.getCode());
				Dict dict = baseDao.get(Dict.class, df.getFtype());
				if(dict.getValue().equals("java.lang.String")) {
					sbVal.append("'");
					sbVal.append(parame.get(df.getCode()));
					sbVal.append("'");
				}else if(dict.getValue().equals("java.lang.Long")) {
					sbVal.append(parame.get(df.getCode()));
				}else if(dict.getValue().equals("java.util.Date")) {
					sbVal.append("'");
					sbVal.append(DateUtil.format(new Date(Long.parseLong(String.valueOf(parame.get(df.getCode())))),
												 DateUtil.formatStr_yyyyMMddHHmmss));
					sbVal.append("'");
				}
				if(index < dfList.size()) {
					sb.append(", ");
					sbVal.append(", ");
				}
				index ++;
			}
			sb.append(")");
			sbVal.append(")");
			sb.append(sbVal);
			String sql = sb.toString();
			System.out.println(sql);
			return baseDao.executeSql(sql);
		}
		return 0;
	}

	@Override
	public int updateSql(String nodeId, String id, Map<String, Object> parame) {
		Pnode pnode = baseDao.get(Pnode.class, nodeId);
		StringBuffer sb = new StringBuffer();
		sb.append("update ");
		sb.append("dny_"+pnode.getCode()+" set ");
		for(String i : parame.keySet()) {
			if(!i.equals("parent") && !i.equals("id") && !i.equals("deleted") && !i.equals("pnode")) {
				List<Dfiled> dfList = baseDao.find("from Dfiled where nodeId='"+nodeId+"' and code='"+i+"'");
				if(null !=dfList && dfList.size() ==1) {
					Dfiled df = dfList.get(0);
					Dict dict = baseDao.get(Dict.class, df.getFtype());
					if(dict.getValue().equals("java.lang.String")) {
						sb.append(i+"='" + parame.get(i)+"'");
					}else {
						sb.append(i+"="+parame.get(i));
					}
					sb.append(",");
				}
			}
		}
		String sqls = sb.toString();
		if(sqls.endsWith(",")) {
			sqls = sqls.substring(0, sqls.length()-1);
		}
		sqls = sqls+" where id='"+id+"'";
		System.out.println(sqls);
		return baseDao.executeSql(sqls);
	}

	@Override
	public void setEditHtmlAttribute(HttpServletRequest request, String parent, String node) {
		Pnode pnode = baseDao.get(Pnode.class, node);
		List<Dfiled> dflist = baseDao.find("from Dfiled where nodeId='" + node + "' order by orderId");
		request.setAttribute("colsNum", 1);
		request.setAttribute("htmlPrefix", pnode.getCode());
		if (dflist != null && dflist.size() > 0) {
			List<FieldSetting> fslist = this.getFileldSetting(dflist);
			request.setAttribute("fields", fslist);
		}

	}
	
	public List<FieldSetting> getFileldSetting(List<Dfiled> dflist){
		List<FieldSetting> list = new LinkedList<>();
		int rowIndex = 1;
		if(dflist !=null && dflist.size() > 0) {
			for(Dfiled i : dflist) {
				FieldSetting fs = new FieldSetting();
				fs.setRowIndex(rowIndex);
				fs.setColumnName(i.getCode());
				fs.setLabelName(i.getName());
				fs.setIsCondition("0");
				fs.setIsSelected("1");
				fs.setValidateType("");
				setTagType(fs, i);
				list.add(fs);
				rowIndex++;
			}
		}
		return list;
	}
	
	private void setTagType(FieldSetting fs, Dfiled filed) {
		Dict dict = baseDao.get(Dict.class, filed.getFormType());
		fs.setTagType(dict.getRemark());
		fs.setType(dict.getValue());
	}
	
	

}
